<template>
  <div>
    <div class="search">
      <input v-model="keyword" class="search-input" type="text" placeholder="输入城市名或拼音" />
    </div>
    <!-- v-model="keyword"双向绑定 -->
    <!-- 搜索的内容显示在这里 -->
    <div class="search-content" ref="search" v-show="keyword">
      <ul>
        <li
          class="search-item border-bottom"
          v-for="item of list"
          :key="item.id"
          @click="handleCityClick(item.name)"
        >{{item.name}}</li>
        <li class="search-item border-bottom" v-show="hasNoData">没有找到匹配数据</li>
      </ul>
    </div>
  </div>
</template>
<script>
import { mapState, mapMutations } from "vuex";
import BScroll from "better-scroll";

export default {
  name: "CitySearch",
  props: {
    cities: Object
  },
  methods: {
    handleCityClick(city) {
      this.changeCity(city);
      this.$router.push("/");
    },
    ...mapMutations(["changeCity"])
  },
  data() {
    // 要把input框里面输入的内容和数据进行绑定，故在逻辑里面定义一个data
    return {
      keyword: "",
      list: [],
      timer: null
    };
  },
  computed: {
    hasNoData() {
      return !this.list.length;
    }
  },
  watch: {
    //监听keyword的改变
    keyword() {
      if (this.timer) {
        clearTimeout(this.timer);
      }
      if (!this.keyword) {
        this.list = [];
        return;
      }
      this.timer = setTimeout(() => {
        //当keyword发生改变时，100毫秒后执行这个箭头函数
        const result = [];
        for (let i in this.cities) {
          //循环cities里面的内容
          this.cities[i].forEach(value => {
            if (
              //也就是如果spell,name可以搜索到这个关键字，我们就把这一项添加到result里
              value.spell.indexOf(this.keyword) > -1 ||
              value.name.indexOf(this.keyword) > -1
            ) {
              result.push(value);
            }
          });
        }
        this.list = result;
        //list中就存储了包含关键字的城市的信息，就可以在list里做循环了
      }, 100);
    }
  },
  mounted() {
    this.scroll = new BScroll(this.$refs.search);
  }
};
</script>
<style lang='stylus' scoped>
@import '~styles/varibles.styl';

.search {
  padding: 0 0.1rem;
  height: 0.72rem;
  background: $bgColor;

  .search-input {
    // 假如您需要并排放置两个带边框的框，可通过将 box-sizing 设置为 "border-box"。
    // 这可令浏览器呈现出带有指定宽度和高度的框，并把边框和内边距放入框中。
    box-sizing: border-box;
    padding: 0 0.15rem;
    height: 0.6rem;
    line-height: 0.6rem;
    width: 100%;
    text-align: center;
    border-radius: 0.06rem;
    color: #666;
  }
}

.search-content {
  z-index: 1;
  overflow: hidden;
  position: absolute;
  top: 1.58rem;
  left: 0;
  right: 0;
  bottom: 0;

  .search-item {
    line-height: 0.62rem;
    padding-left: 0.2rem;
    background: #fff;
    color: #666;
  }
}
</style>